package cn.itcast.web.controller.cargo;

import cn.itcast.common.utils.ImageUploadUtils;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

	@Reference
	private ContractProductService contractProductService;

	@Reference
	private FactoryService factoryService;

	/**
	 * 查询某个购销合同下的所有货物
	 *  参数 ： 购销合同的ID
	 *  查询：
	 *      根据购销合同id查询所有的货物
	 */
	@RequestMapping("/list")
	public String list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size
			,String contractId) {
		//根据购销合同id查询所有的货物
		ContractProductExample example = new ContractProductExample();
		//创建Criteria对象
		ContractProductExample.Criteria criteria = example.createCriteria();
		//向Criteria对象设置条件
		criteria.andContractIdEqualTo(contractId);
		PageInfo info = contractProductService.findAll(page, size, example);
		request.setAttribute("page",info);

		//查询所有的生产厂家
		FactoryExample factoryExample = new FactoryExample();
		FactoryExample.Criteria exampleCriteria = factoryExample.createCriteria();
		exampleCriteria.andCtypeEqualTo("货物");
		List factoryList = factoryService.findAll(factoryExample);
		request.setAttribute("factoryList",factoryList);

		//将合同id存入request，方便进行保存
		request.setAttribute("contractId",contractId);
		return "cargo/product/product-list";
	}


	/**
	 * 进入更新页面
	 */
	@RequestMapping("/toUpdate")
	public String toUpdate(String id) {
		//根据id查询货物
		ContractProduct contractProduct = contractProductService.findById(id);
		request.setAttribute("contractProduct",contractProduct);
		//查询所有工厂数据
		FactoryExample factoryExample = new FactoryExample();
		FactoryExample.Criteria exampleCriteria = factoryExample.createCriteria();
		exampleCriteria.andCtypeEqualTo("货物");
		List factoryList = factoryService.findAll(factoryExample);
		request.setAttribute("factoryList",factoryList);
		return "cargo/product/product-update";
	}

	/**
	 * 保存或更新
	 *      contractProduct:货物对象
	 *      productPhoto：上传的货物图片
	 */
	@RequestMapping("/edit")
	public String edit(ContractProduct contractProduct, MultipartFile productPhoto) throws IOException {

		contractProduct.setCompanyId(getLoginCompanyId());
		contractProduct.setCompanyName(getLoginCompanyName());

		if(StringUtils.isEmpty(contractProduct.getId())) {
			//将图片上传到七牛云
			if(productPhoto != null && !productPhoto.isEmpty()) {
				String imageUrl = new ImageUploadUtils().upload(productPhoto.getBytes());
				//设置货物图片的访问路径
				contractProduct.setProductImage(imageUrl);
			}
			//保存
			contractProductService.save(contractProduct);
		}else{
			//更新
			contractProductService.update(contractProduct);
		}
		return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
	}

	/**
	 * 删除
	 *      参数：
	 *          id ： 货物id
	 *          contractId: 购销合同id （为了方便页面跳转）
	 */
	@RequestMapping("/delete")
	public String delete(String id,String contractId) {
		contractProductService.delete(id);
		return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
	}

	/**
	 * 进入上传的页面
	 *      参数：合同id
	 */
	@RequestMapping("/toImport")
	public String toImport(String contractId) {
		request.setAttribute("contractId",contractId);
		return "cargo/product/product-import";
	}

	/**
	 * 实现excel文件上传，通过poi解析，保存到数据库中
	 *      参数：
	 *          购销合同id，
	 *          上传的excel文件
	 */
	@RequestMapping("/import")
	public String importExcel(String contractId,MultipartFile file) throws Exception {
		//i.解析excel文件，根据文件中的内容构造货物列表
		List<ContractProduct> list = new ArrayList();
		//1.根据上传的文件构造excel工作簿
		Workbook wb = new XSSFWorkbook(file.getInputStream());
		//2.获取第一页
		Sheet sheet = wb.getSheetAt(0);
		//3.循环获取每一行
		for (int i = 1; i < sheet.getLastRowNum() +1 ; i++) {
			Row row = sheet.getRow(i);
			//和单元格索引一一对应  {“”，“生产厂家”，“货号”,“数量”,"包装单位(PCS/SETS)",	"装率","箱数","单价","货物描述","要求}
			Object [] objs = new Object[10];
			for (int j = 1; j < row.getLastCellNum(); j++) {
				//4.循环获取每一个单元格
				Cell cell = row.getCell(j);
				//5.获取每个单元格中的数据
				objs[j] = getCellValue(cell);
			}
			//根据object数组构造货物
			ContractProduct cp = new ContractProduct(objs,getLoginCompanyId(),getLoginCompanyName());
			//设置购销合同id
			cp.setContractId(contractId);
			list.add(cp);
		}
		//ii.调用service完成货物的批量保存
		contractProductService.saveAll(list);
		return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
	}


	//解析每个单元格的数据
	public static Object getCellValue(Cell cell) {
		Object obj = null;
		CellType cellType = cell.getCellType(); //获取单元格数据类型
		switch (cellType) {
			case STRING: { //字符串单元
				obj = cell.getStringCellValue();
				break;
			}
			//excel默认将日志也理解为数字
			case NUMERIC:{ //数字单元格
				if(DateUtil.isCellDateFormatted(cell)) { //日期
					obj = cell.getDateCellValue();
				}else {
					obj = cell.getNumericCellValue();
				}
				break;
			}
			case BOOLEAN:{ //boolean
				obj = cell.getBooleanCellValue();
				break;
			}
			default:{
				break;
			}
		}

		return obj;
	}
}

